package tingshu.servlet.track;

import tingshu.repository.TrackRepo;
import tingshu.util.Log;
import tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * 上传音频
 * @author houdaiqin
 * @date 2022/07/13 20:24
 **/
@WebServlet("/studio/track/upload.do")
@MultipartConfig
public class UploadDoServlet extends HttpServlet {
    private TrackRepo uploadRepo=new TrackRepo();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserVO userVO=null;

        HttpSession session=req.getSession(false);
        if (session!=null){
            userVO=(UserVO)session.getAttribute("currentUser");
        }

        //设置响应格式
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain");
        PrintWriter writer= resp.getWriter();
        //当用户没有登录时
        if (userVO==null){
            Log.println("用户未登录");
            writer.println("用户未登录");
            return;
        }

        //用户已经登录
        Log.println("登录用户为"+userVO);

        req.setCharacterEncoding("utf-8");
        String title = req.getParameter("title");
        if (title==null || title.equals("")){
            throw new ServletException("音频名称为空");
        }
        Log.println("获取的title为"+title);

        Part track = req.getPart("track");
        //获取音频的类型
        String type = track.getContentType();
        Log.println("获取的type是"+type);
        if (!type.startsWith("audio/")){
            throw new ServletException("音频文件为空 或 音频文件不符合格式");
        }
        //获取音频的内容
        InputStream contentInputStream = track.getInputStream();

        //将获取的数据插入数据库
        uploadRepo.insert(userVO.uid,title,type,contentInputStream);
        Log.println("上传成功");

        //writer.println("上传成功");
        resp.sendRedirect("/studio/track/list.html");
    }
}